#!/usr/bin/env python3

import subprocess
import json
import docker
import os
import datetime
import uuid

DATE_FORMART = "%Y-%m-%d_%H:%M:%S"
ROOTFS_RELEASE_FILE = "rootfs-release"


def generate_rootfs_release(config):
    target = {}

    target["date"] = datetime.datetime.now().strftime(DATE_FORMART)
    target["git"] = subprocess.check_output(['git','rev-parse','HEAD']).decode().strip()
    target["uuid"] = str(uuid.uuid1())
    target["config"] = config

    with open(ROOTFS_RELEASE_FILE, "w") as fd :
        json.dump(target,fd, indent =4)


if __name__ == "__main__":

    docker_status = subprocess.check_output(['systemctl','is-active','docker']).decode().strip()
    if docker_status != "active":
        print("Error : Docker Service is not running")
        exit(1)

    with open("config.json") as fd:
        config = json.load(fd)

    target_version = config["TargetVersion"]

    generate_rootfs_release(config)

    print("Setup build environment...")

    client = docker.from_env()
    cc = client.containers.run("openeuler/openeuler:"+target_version,
                                            remove=True,
                                            privileged = True,
                                            detach = True,
                                            volumes=[os.getcwd() + ':/work'],
                                            working_dir="/work",
                                            command="./build.py"
                                            )

    print("Start Build rootfs...")

    for item in cc.logs(stream =True):
        print(item.decode(), end="")

    ret = cc.wait()

    print("Build Finish")